package com.jckl.foodathon.fragments;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.jckl.foodathon.R;
import com.jckl.foodathon.activities.HomeActivity;
import com.jckl.foodathon.model.Coordinate;
import com.jckl.foodathon.services.location.GPSTracker;
import com.jckl.foodathon.services.location.LocalityQuery;

public class HomeFragment extends Fragment implements OnClickListener{
	
	// GPSTracker class
    GPSTracker gps;
    double latitude;
    double longitude;

    TextView my_locality;
    
    String locality;
    View fragmentView;
    
    Button callFragment;
    
	public HomeFragment() {
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View rootView = inflater.inflate(R.layout.fragment_home, container, false);
		fragmentView = rootView;
		
		callFragment 	= (Button) rootView.findViewById(R.id.call_other);
		my_locality 	= (TextView) rootView.findViewById(R.id.my_locality);
		
		callFragment.setOnClickListener(this);
		
		LocalityQuery localityQuery = new LocalityQuery();
		
		// create class object
        gps = new GPSTracker(getActivity().getApplicationContext(), fragmentView);
        // check if GPS enabled     
        if(gps.canGetLocation()){
        	
        	gps.getLocation();
            latitude = gps.getLatitude();
            longitude = gps.getLongitude();
            
            //share the coordinate with the parent activity
            Coordinate coordinate = new Coordinate(latitude, longitude);
            ((HomeActivity)this.getActivity()).setCoordinate(coordinate);
            
            //update the locality 
            localityQuery.getLocality(getActivity(), fragmentView, latitude, longitude);

            
        }else{
            // can't get location
            // GPS or Network is not enabled
            // Ask user to enable GPS/network in settings
            gps.showSettingsAlert();
        }
		
		return rootView;
	}

	@Override
	public void onClick(View v) {
        switch(v.getId()){
        case R.id.call_other:
        	FragmentTransaction ft = getActivity().getSupportFragmentManager().beginTransaction();
        	ft.replace(R.id.home_placeholder, new NearbyStoreFragment());
        	ft.addToBackStack(null);
    		ft.commit();
        break;
        }
	}
	
}